package com.qdlc.p2p.dal.mybatis.pager.core;

import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;



/**
 * Executor拦截器
 * @author linya 2015-06-09 19:50:49
 */
@Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class PageExecutorInterceptor implements Interceptor {

	public Object intercept(Invocation invocation) throws Throwable {
		
		Object[] args = invocation.getArgs();
		Object parameterObject = args[1]; 
		
		// 判断参数是不是PageParameterWrapper类型
		// 如果是则需要还原参数对象,并且保存分页包装参数到执行上下文中
		if (parameterObject != null && parameterObject instanceof PageParameterWrapper) {
			PageParameterWrapper wrapper = (PageParameterWrapper)parameterObject;
			args[1] = wrapper.getParameterObject();
			PageInterceptorContext.putPageParameterWrapper(wrapper);
		}
		
		return invocation.proceed();
	}
	
	@Override
	public Object plugin(Object target) {
		if (target instanceof Executor) {
			return Plugin.wrap(target, this);
		}
		return target;
	}

	@Override
	public void setProperties(Properties properties) {
		
	}

}
